﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using EntityEditorLib;
using System.Collections.Generic;
using SharePointEntityProject.EntityEditorLib;
using System.Diagnostics;

namespace SharePointEntityProject.VisualEntityEditor
{
    [ToolboxItem(false)]
    public partial class VisualEntityEditor : System.Web.UI.WebControls.WebParts.WebPart
    {

        private string _EntityEditorListName;
        [WebBrowsable(true), Category("Entity Editor Settings"), Personalizable, Description("Name of the storage list")]
        public string EntityEditorListName
        {
            get
            {

                return _EntityEditorListName;
            }
            set
            {
                _EntityEditorListName = value;
            }
        }

        private string _SiteURL;
        [WebBrowsable(true), Category("Entity Editor Settings"), Personalizable, Description("Set the site URL of the site")]
        public string SiteURL
        {
            get
            {
                return _SiteURL;
            }
            set
            {
                _SiteURL = value;
            }
        }

        
        private EntityEditor  entityEdit;
        private Dictionary<string, ContentTypeInfo> validEntityListData;
        //private Dictionary<string, FieldInfo> allFields = new Dictionary<string, FieldInfo>();

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
            if (String.IsNullOrEmpty(SiteURL))
            {
                this.SiteURL = SPContext.Current.Site.Url;
                this.StatusMessageTxt.Text = "Configure the webpart";

            }else{

            //Populate dropdown with all CT
            entityEdit = new EntityEditor(this.SiteURL,this.EntityEditorListName);
              validEntityListData = entityEdit.GetValidContentTypes();
           
            
            //Manual add all entities
            foreach (ContentTypeInfo curInfo in validEntityListData.Values)
            {
                //add to drop down
                ValidEntityDrpDown.Items.Add(new ListItem(curInfo.ToString(), curInfo.Id));
           }

            //Hide fields as entity is not selected
            //TODO: ValidFieldDrpDown.Visible = false;

            FieldPanel.Visible = false;
            FieldInfoPanel.Visible = false;

            EntityInfoPanel.Visible = false;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
             
        }

        /// <summary>
        /// User has selected an entity, this updates the fields view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EntitySelectionChanged(object sender, EventArgs e)
        {

            DropDownList dropList = sender as DropDownList;
            //User has chosen an entity, show the current settings. 

            //Get the ID
            string selectedItemID = dropList.SelectedValue;

            //Update the txt field
            //TODO: add more info 
            this.SelectedEntityName.Text = validEntityListData[selectedItemID].Name;
            this.SelectedEntityDescription.Text = validEntityListData[selectedItemID].Description;

            Dictionary<string, FieldInfo> currentFields = UpdateEntityFieldDisplay( );

            UpdateAvailableFieldsDrpDown(currentFields);

            FieldPanel.Visible = true;
            FieldInfoPanel.Visible = false;
            EntityInfoPanel.Visible = true;


            //DEBUG
            //FieldInfo[] allFieldsArray = allFields.ToArray();
            //AllFieldsGrid.DataSource = allFieldsArray;
            //AllFieldsGrid.DataBind();

        }

        private void UpdateAvailableFieldsDrpDown(Dictionary<string, FieldInfo> currentFields)
        {
            //update available fields
            Dictionary<string, FieldInfo> allFields = entityEdit.GetAllFieldsOnSite();
            ValidFieldDrpDown.Items.Clear();
            //Update dropdown 
            foreach (FieldInfo curField in allFields.Values)
            {
                //if not already added to the content type
                if (currentFields.ContainsKey(curField.Id))
                {
                    Debug.WriteLine(String.Format("Ignoring field as it is already on the entity : {0}", curField));
                }
                else
                {
                    ValidFieldDrpDown.Items.Add(new ListItem(curField.ToString(), curField.Id));
                }
            }
            FieldInfoPanel.Visible = true;//show dropdown
        }

        private Dictionary<string, FieldInfo> UpdateEntityFieldDisplay()
        {
            //Get the ID
            string selectedItemID = this.ValidEntityDrpDown.SelectedValue;

            //Get the entity fields
            Dictionary<string, FieldInfo> currentFields = entityEdit.GetEntityFields(selectedItemID);

            //Data bind to an array, NO REFLECTION
            FieldInfo[] currentFieldsArray = new FieldInfo[currentFields.Count];
            currentFields.Values.CopyTo(currentFieldsArray, 0);

            FieldsGridView.DataSource = currentFieldsArray;
            FieldsGridView.DataBind();
            return currentFields;
        }

        /// <summary>
        /// User has selected an entity and a filed to add
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void FieldsSelectedIndexChanged(object sender, EventArgs e)
        //{
        //    //field id
        //    string fieldId = ValidFieldDrpDown.SelectedValue;
        //    //display field info , pre accept for add. 
        //    FieldInfo curInfo = allFields[fieldId];
        //    FieldNameTxt.Text = curInfo.Name;
        //    FieldDescriptionTxt.Text = curInfo.Description;
        //    FieldGroupTxt.Text = curInfo.Group;
        //    FieldTypeTxt.Text = curInfo.Type;


        //}

        protected void AddFieldToEntityBtn_Click(object sender, EventArgs e)
        {


            try
            {
                //TODO get the correct field info


                string fieldId = ValidFieldDrpDown.SelectedValue;
                string contentTypeId = ValidEntityDrpDown.SelectedValue;

                entityEdit.AddFieldToContentType(contentTypeId, fieldId);

                //update display
                Dictionary<string, FieldInfo> currentFields = UpdateEntityFieldDisplay();

                UpdateAvailableFieldsDrpDown(currentFields);

            }
            catch (Exception ex)
            {
                //notify of error
                FieldStatusText.Text = ex.Message;
            }

            FieldStatusText.Text = "Field added";
        }

        protected void FieldSelectedDropDownChanged(object sender, EventArgs e)
        {
            //field id
            string fieldId = ValidFieldDrpDown.SelectedValue;
            //display field info , pre accept for add. 
            Dictionary<string,FieldInfo> allFields = entityEdit.GetAllFieldsOnSite();
            FieldInfo curInfo = allFields[fieldId];
            FieldNameTxt.Text = curInfo.Name;
            FieldDescriptionTxt.Text = curInfo.Description;
            FieldGroupTxt.Text = curInfo.Group;
            FieldTypeTxt.Text = curInfo.Type;

            FieldInfoPanel.Visible = true;

        }

        

        //protected void CreateFieldBtn_Click(object sender, EventArgs e)
        //{
        //    //Create a filed based on the values. 
        //    try
        //    {
        //        //get all the info on the field
        //        FieldInfo fieldInfo = new FieldInfo()
        //        {
        //            Name = NewFieldName.Text,
        //            Description = NewFieldDescription.Text,
        //        };

        //        entityEdit.AddFieldToContentType(ValidEntityDrpDown.SelectedValue, fieldInfo);

        //    }
        //    catch ( Exception ex)
        //    {
        //        //notify of error
        //        FieldStatusText.Text = ex.Message;
        //    }
        //}


        //TODO: Add optional doc ref option
    }

}
